﻿using Microsoft.Extensions.DependencyInjection;
using MyK3CloudCore.IOC.Attributes;
using MyK3CloudCore.IOC.DataEntity;
using Polly;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;

namespace MyK3CloudCore.IOC.Extensions
{
    public static class Extensions
    {
        #region 类型别名
        /// <summary>
        /// 获取类型别名
        /// Attribute
        /// </summary>
        [DebuggerStepThrough]
        public static string GetAlias(this object obj)
        {
            if (obj == null) { return string.Empty; }
            return obj.GetType().GetCustomAttribute<AliasAttribute>()?.Name ?? obj.GetType().Name;
        }
        /// <summary>
        /// 获取(AliasAttribute)特性值
        /// </summary>
        /// <param name="inherit">是否继承</param>
        [DebuggerStepThrough]
        public static string GetAlias(this Type t, bool inherit = false)
        {
            if (t == null) { return string.Empty; }
            return t.GetCustomAttribute<AliasAttribute>(inherit)?.Name ?? t.Name;
        }
        #endregion

        /// <summary>
        /// 将\u1234类型的字符转化成汉字
        /// </summary>
        public static string DeCode(string str)
        {
            var regex = new Regex(@"\\u(\w{4})");
            string result = regex.Replace(str, delegate (Match m)
            {
                string hexStr = m.Groups[1].Value;
                string charStr = ((char)int.Parse(hexStr, System.Globalization.NumberStyles.HexNumber)).ToString();
                return charStr;
            });
            return result;
        }

        /// <summary>
        /// 可空类型转换
        /// </summary>
        [DebuggerStepThrough]
        public static Type ParseNullableToType(this Type source)
        {
            if (source.IsGenericType && source.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                NullableConverter nullableConverter = new(source);
                source = nullableConverter.UnderlyingType;
            }
            return source;
        }
        /// <summary>
        /// foreach 空检查
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static IEnumerable<T> CheckNull<T>(this IEnumerable<T> list)
        {

            return list ?? new List<T>(0);
        }

        public static LoginResult GetLoginResult(this K3Client.K3CloudApiClient client) => client?.LastLoginInfo;

        public static IHttpClientBuilder AddDefaultHttpClient(this IServiceCollection services, CookieContainer _cookie = default)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            return services.AddHttpClient(IocConst.K3WEBAPI_CLIENT, client =>
             {
                 client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
             }).ConfigurePrimaryHttpMessageHandler((sp) =>
             {
                 HttpClientHandler handler = new()
                 {
                     CookieContainer = _cookie,
                     Proxy = WebRequest.DefaultWebProxy,
                     AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
                 };
                 return handler;
             }).AddTransientHttpErrorPolicy(policyBuilder =>
                        policyBuilder.WaitAndRetryAsync(3, retryNumber => TimeSpan.FromMilliseconds(600))
             );
        }
    }
}
